package com.cff.shorturl.manager;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.cff.shorturl.db.DbFactory;
import com.cff.shorturl.db.DbManager;
import com.cff.shorturl.util.DateUtil;

public class SequenceManager {
	String urlId = "short";
	private ConcurrentLinkedQueue<Integer> urlIdSeq = new ConcurrentLinkedQueue<Integer>();
	private static int maxSeqSize = 50;
	private static int dengerSeqSize = 10;

	public void init() throws Exception {
		fillUrlIdSeq();
	}

	private SequenceManager() {
		try {
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static class SequenceManagerHolder {
		private static SequenceManager instance = new SequenceManager();
	}

	public static SequenceManager getInstance() {
		return SequenceManagerHolder.instance;
	}

	public synchronized void fillUrlIdSeq() throws Exception {
		int size = maxSeqSize - urlIdSeq.size();
		urlId = urlId + DateUtil.format(new Date(), DateUtil.SimpleMonthPattern);
		DbManager db = DbFactory.createDbManager();
		int para = db.queryInt("select nextgroup(?,?)", new Object[] { urlId, maxSeqSize });
		System.out.println("发号器加载了" + maxSeqSize + "个号，起始号码为" +  para);
		if (para == -1)
			throw new IOException("查询id失败");
		for (int i = 0; i < size; i++) {
			urlIdSeq.add(para);
			para++;
		}
	}

	public int offerUrlIdSeq() throws Exception {
		if (urlIdSeq.size() < dengerSeqSize) {
			fillUrlIdSeq();
		}
		Integer el = urlIdSeq.poll();
		if (el == null) {
			return offerUrlIdSeq();
		}
		return el;
	}

}
